package com.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.component.domain.SysUserEntity;
import com.component.domain.vo.MUserVo;
import com.component.domain.vo.UserVo;
import com.component.service.SysUserService;
import com.system.common.Result;
import com.system.util.DictiUtils;
import com.system.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * @Classname MUserApi
 * @Description TODO
 * @Date 2023/9/28 23:02
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Api(tags = {"用户模块"})
@RestController
@RequestMapping("/user")
public class MUserApi {


    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("用户分页模块")
    @GetMapping("/page")
    public JSONObject page(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "2") Integer pageSize,
                           @RequestParam(value = "username",required = false)String username,
                           @RequestParam(value = "realname",required = false)String realName,
                           @RequestParam(value = "phone",required = false)String phone){
        IPage<SysUserEntity> page=sysUserService.page(pageNum,pageSize,username,realName,phone);
        return Result.successInfo(page);
    }

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @ApiOperation("用户新增")
    @PostMapping("/add")
    public JSONObject addUser(@RequestBody MUserVo userVo){
        SysUserEntity sysUserEntity=sysUserService.selectUserByName(userVo.getUsername());
        if(sysUserEntity!=null){
            return ResultUtil.resultCodeJSON(1,"账号已经存在");
        }
        SysUserEntity sysUser=new SysUserEntity();
        sysUser.setUsername(userVo.getUsername());
        JSONObject obj= DictiUtils.getDicti("system_init_password","init_password");
        if (!obj.containsKey("value")) {
            return Result.errorInfo("初始密码不存在,请设置字典 parentkey: system_init_password  key:init_password 的值");
        }
        String initPassword=obj.getString("value");
        BeanUtils.copyProperties(userVo,sysUser);
        sysUserEntity.setPassword(bCryptPasswordEncoder.encode(initPassword));
        sysUserService.save(sysUserEntity);
        return Result.successInfo();
    }
}
